﻿#if UNITY_EDITOR
using UnityEditor;
#endif
using UnityEngine;
using System.Collections;

namespace Hont.BlazingNodePackage
{
    public class InRangeNode : Node
    {
        public float range = 10f;

        public override Vector2 Size { get { return new Vector2(130, 59); } }
        public override string Name { get { return "InRange"; } }
        public override string Category { get { return "Logic"; } }


        protected override void Init()
        {
            base.Init();

            mInPortList.Add(new Port() { Host = this, Name = "Compare" });

            mOutPortList.Clear();
            mOutPortList.Add(new Port() { Host = this, Name = "True" });
            mOutPortList.Add(new Port() { Host = this, Name = "False" });
        }

        public override IEnumerator Execute(Port port)
        {
            yield return ExecutePort(mInPortList[1]);

            var compareTransform = default(Transform);

            if (mInPortList[1].Value is GameObject)
            {
                compareTransform = (mInPortList[1].Value as GameObject).transform;
            }
            else if (mInPortList[1].Value is Transform)
            {
                compareTransform = mInPortList[1].Value as Transform;
            }

            var standardContext = Context as StandardContext;
            if (standardContext == null)
                throw new System.ArgumentException("In Range Node Just Support Standat Context or inheirt that!");

            var distance = Vector3.Distance(standardContext.GameObject.transform.position, compareTransform.position);

            if (distance <= range)
            {
                yield return ExecutePort(mOutPortList[0]);
            }   
            else
            {
                yield return ExecutePort(mOutPortList[1]);
            }
        }

        public override void OnDrawAttributesGUI(out bool updateUI)
        {
            updateUI = false;

#if UNITY_EDITOR
            range = EditorGUILayout.FloatField("Range", range);
#endif
        }
    }
}
